package com.xidian.zhiancloud.controller.emergencyManagement;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xidian.zhiancloud.constant.EmergencyManagementConstant;
import com.xidian.zhiancloud.constant.LedgerManagementConstant;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dao.WarehouseOutMapper;
import com.xidian.zhiancloud.dao.WarehousingMapper;
import com.xidian.zhiancloud.dao.syset.SysPositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.emergencyManagement.EmergencyMaterialsInventoryManagementDTO;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exceldto.EmergencyManagement.WarehouseExcel;
import com.xidian.zhiancloud.exceldto.EmergencyManagement.WarehouseExcelDTO;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.PositionList;
import com.xidian.zhiancloud.model.syset.SysPosition;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.emergencyManagement.EmergencyMaterialsInventoryManagementQO;
import com.xidian.zhiancloud.service.emergencyManagement.EmergencyMaterialsInventoryManagementService;
import com.xidian.zhiancloud.service.user.PositionService;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.util.zyf.ExcelUtils;
import com.xidian.zhiancloud.util.zyf.StringUtils;
import com.xidian.zhiancloud.vo.emergencyManagement.*;
import com.xidian.zhiancloud.vo.ledgerManagerment.targetAndSystem.SecurityCulturalActivityLedgerVO;
import com.xidian.zhiancloud.vo.ledgerManagerment.targetAndSystem.SecurityMeetingLedgerVO;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 应急管理 应急物资库存管理接口
 */
@RestController
@RequestMapping("/EmergencyMaterialsInventoryManagement")
public class EmergencyMaterialsInventoryManagementController extends BaseController {

    @Autowired
    private EmergencyMaterialsInventoryManagementService emergencyMaterialsInventoryManagementService;

    @Autowired
    private SysPositionMapper sysPositionMapper;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserService userService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private WarehousingMapper warehousingMapper;

    @Autowired
    private WarehouseOutMapper warehouseOutMapper;

    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 增加应急物资库存管理
     * @param emergencyMaterialsInventoryManagement 应急物资对象
     * @return 返回是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(EmergencyMaterialsInventoryManagement emergencyMaterialsInventoryManagement){
        emergencyMaterialsInventoryManagement.setCreatorId(getSessionUserid());
        emergencyMaterialsInventoryManagement.setCreateTime(new Date(System.currentTimeMillis()));
        emergencyMaterialsInventoryManagement.setCompanyId(getSessionUserCompanyId());
        Boolean res=emergencyMaterialsInventoryManagementService.add(emergencyMaterialsInventoryManagement);
        return ResultDTO.successOf(res,GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id获取应急物资库存管理
     * @param id 应急物资库存的id
     * @return 应急物资库存对象
     */
    @GetMapping("/getById")
    public ResultDTO<EmergencyMaterialsInventoryManagementVO> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(emergencyMaterialsInventoryManagementService.getById(id),GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id删除应急物资库存管理
     * @param ids ids数组
     * @return 返回是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res=emergencyMaterialsInventoryManagementService.deleteByIds(ids);
        return ResultDTO.successOf(res,GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id修改应急物资库存管理
     * @param emergencyMaterialsInventoryManagement 应急物资库存对象
     * @return 返回是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(EmergencyMaterialsInventoryManagement emergencyMaterialsInventoryManagement) {
        emergencyMaterialsInventoryManagement.setCompanyId(null);
        emergencyMaterialsInventoryManagement.setCreatorId(null);
        emergencyMaterialsInventoryManagement.setCreateTime(null);
        Boolean res=emergencyMaterialsInventoryManagementService.updateById(emergencyMaterialsInventoryManagement);
        return ResultDTO.successOf(res,GeneralResponseEnums.SUCCESS);
    }

    /**
     * 条件查询
     * @param emergencyMaterialsInventoryManagementQO 查询条件
     * @return  返回查询列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<EmergencyMaterialsInventoryManagementVO>> getListByQueryObject(EmergencyMaterialsInventoryManagementQO emergencyMaterialsInventoryManagementQO) {
        if (emergencyMaterialsInventoryManagementQO.getCurrent() == null || emergencyMaterialsInventoryManagementQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        emergencyMaterialsInventoryManagementQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(emergencyMaterialsInventoryManagementService.getListByQO(emergencyMaterialsInventoryManagementQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     *
     * @param response
     * @param ids      id列表
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        List<EmergencyMaterialsInventoryManagement> list=emergencyMaterialsInventoryManagementService.listByIds(Arrays.asList(ids));
        List<EmergencyMaterialsInventoryManagementVO> ans=new LinkedList<>();
        list.forEach(o -> {
            EmergencyMaterialsInventoryManagementVO vo = new EmergencyMaterialsInventoryManagementVO();
            BeanUtils.copyProperties(o, vo);
            SysPosition p=sysPositionMapper.selectById(vo.getLocaleOrganizationId());
            vo.setOrganizationLocale(p==null?"该位置不存在":p.getName());
            Organization org = organizationService.getById(vo.getOrganizationId());
            vo.setOrganizationName(org == null ? "该部门不存在" : org.getName());
            SysUser user = userService.getById(vo.getCreatorId());
            vo.setCreatorName(user == null ? "该用户已被删除" : user.getName());
            SysUser user2 = userService.getById(vo.getLiableP());
            vo.setLiablePersonnel(user2 == null ? "该用户已被删除" : user2.getName());
            vo.setStatusName(EmergencyManagementConstant.statusType.get(vo.getStatus()));
            vo.setUnitName(EmergencyManagementConstant.UnitType.get(vo.getUnit()));
            ans.add(vo);
        });
        ExcelUtils.exportExcel(ans,"应急物资管理","应急物资管理", EmergencyMaterialsInventoryManagementVO.class,"应急物资管理",response);
    }

    /**
     * 出入库导出
     *
     * @param response
     * @param ids      id列表
     * @throws IOException
     */
    @GetMapping("/exportWarehouse")
    public void exportWarehouse(HttpServletResponse response, Long[] ids) throws IOException {
        List<EmergencyMaterialsInventoryManagement> list=emergencyMaterialsInventoryManagementService.listByIds(Arrays.asList(ids));
        List<WarehouseExcelDTO> warehouseExcelDTOList=new LinkedList<>();
        list.forEach(o -> {
            WarehouseExcelDTO warehouseExcelDTO = new WarehouseExcelDTO();
            warehouseExcelDTO.setName(o.getName());
            SysPosition p=sysPositionMapper.selectById(o.getLocaleOrganizationId());
            warehouseExcelDTO.setOrganizationLocale(p==null?"该位置不存在":p.getName());
            Organization org = organizationService.getById(o.getOrganizationId());
            warehouseExcelDTO.setOrganizationName(org == null ? "该部门不存在" : org.getName());
            SysUser user = userService.getById(o.getLiableP());
            warehouseExcelDTO.setLiablePersonnel(user == null ? "该用户已被删除" : user.getName());

            List<WarehouseExcel> warehouseExcelList=new LinkedList<>();

            LambdaQueryWrapper<Warehousing> queryWrapper= Wrappers.lambdaQuery();
            queryWrapper.eq(Warehousing::getEmergencyMaterialsId,o.getId());
            if(queryWrapper!=null){
                List<Warehousing> warehousingList=warehousingMapper.selectList(queryWrapper);
                warehousingList.forEach(t -> {
                    WarehouseExcel warehouseExcel=new WarehouseExcel();
                    warehouseExcel.setWarehouseName("入库");
                    warehouseExcel.setStorgeTime(t.getStorgeTime());
                    warehouseExcel.setQuantity(t.getQuantity());
                    SysUser agent=sysUserMapper.selectById(t.getAgentId());
                    warehouseExcel.setAgentName(agent==null?"该用户已删除":agent.getName());
                    warehouseExcelList.add(warehouseExcel);
                });
            }

            LambdaQueryWrapper<WarehouseOut> queryWrapper2= Wrappers.lambdaQuery();
            queryWrapper2.eq(WarehouseOut::getEmergencyMaterialsId,o.getId());
            if(queryWrapper2!=null){
                List<WarehouseOut> warehouseOutList=warehouseOutMapper.selectList(queryWrapper2);
                warehouseOutList.forEach(t -> {
                    WarehouseExcel warehouseExcel=new WarehouseExcel();
                    warehouseExcel.setWarehouseName("出库");
                    warehouseExcel.setStorgeTime(t.getDeliveryTime());
                    warehouseExcel.setQuantity(t.getQuantity());
                    SysUser agent=sysUserMapper.selectById(t.getRecipientId());
                    warehouseExcel.setAgentName(agent==null?"该用户已删除":agent.getName());
                    warehouseExcelList.add(warehouseExcel);
                });
            }
            warehouseExcelDTO.setWarehouseExcelList(warehouseExcelList);
            warehouseExcelDTOList.add(warehouseExcelDTO);
        });
        ExcelUtils.exportExcel(warehouseExcelDTOList,"应急物资出入库记录","应急物资出入库记录", WarehouseExcelDTO.class,"应急物资出入库记录",response);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultDTO<Boolean> upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<EmergencyMaterialsInventoryManagementVO> list = EasyExcel.read(file.getInputStream()).head(EmergencyMaterialsInventoryManagementVO.class).sheet().doReadSync();
                //ExcelUtils.importExcel(file,1,2,EmergencyMaterialsInventoryManagementVO.class);
        List<EmergencyMaterialsInventoryManagement> ans = new LinkedList<>();
        list.forEach(vo -> {
            EmergencyMaterialsInventoryManagement inventory = new EmergencyMaterialsInventoryManagement();
            BeanUtils.copyProperties(vo, inventory);
            inventory.setCreatorId(getSessionUserid());
            inventory.setCompanyId(getSessionUserCompanyId());
            inventory.setCreateTime(new Date(System.currentTimeMillis()));
            vo.setStatus(EmergencyManagementConstant.statusType.indexOf(vo.getStatusName()));
            vo.setUnit(EmergencyManagementConstant.UnitType.indexOf(vo.getUnitName()));
            LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery();
            query.eq(SysUser::getName, vo.getLiablePersonnel());
            SysUser user = userService.getOne(query);
            inventory.setLiableP(user == null ? null : user.getId());

            LambdaQueryWrapper<SysPosition> query2 = Wrappers.<SysPosition>lambdaQuery();
            query2.eq(SysPosition::getName, vo.getOrganizationLocale());
            SysPosition position = sysPositionMapper.selectOne(query2);
            inventory.setLocaleOrganizationId(position == null ? null : position.getId());

            LambdaQueryWrapper<Organization> query3 = Wrappers.<Organization>lambdaQuery();
            query3.eq(Organization::getName, vo.getOrganizationName());
            Organization org = organizationService.getOne(query3);
            inventory.setOrganizationId(org == null ? null : org.getId());
            ans.add(inventory);
        });
        Boolean res = emergencyMaterialsInventoryManagementService.saveBatch(ans);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

}
